const vscode = require('vscode');
const fs = require('fs');
function palindrome(str) {
    var arr = str.replace(/[`:_.~!@#$%^&*() \+ =<>?"{}|, \/ ;' \\ [ \] ·~！@#￥%……&*（）—— \+ ={}|《》？：“”【】、；‘’，。、]/g,
      '');
    return arr
}

function setNovelPath(path) {
    const uri = vscode.Uri.file(path);
    vscode.workspace.fs.createDirectory(uri).then(()=>{},()=>{});

    // 最后一个参数，为true时表示写入全局配置，为false或不传时则只写入工作区配置
    vscode.workspace.getConfiguration().update('moyu-plugin.novelPath', path, true);
    return path;
}

async function parseNovel(path, outpath) {
    // ***引入模块***
    const vscode = require('vscode');
    const readline = require('node:readline');

    // ***路径预处理***
    path = path.substring(1,path.length)

    // ***获取文件名***
    const splitPath = path.split('/')
    console.log(splitPath[splitPath.length - 1]);
    const file = splitPath[splitPath.length - 1];
    const name = palindrome(file.split('.')[0]);

    // ***复制小说源文件到目录***
    let uri = vscode.Uri.file(outpath + '/' + name)
    const createDir = vscode.workspace.fs.createDirectory(uri).then(()=>{},()=>{})
    let copyFlag = false;
    try {
        var uri1 = vscode.Uri.file(vscode.Uri.parse(uri.toString()).path + '/' + name + ".txt")
        uri = vscode.Uri.file(path)
        const copyFile =  vscode.workspace.fs.copy(uri, uri1);
        copyFlag = true
    } catch (error) {
        console.log('warn!! file existed' + vscode.Uri.parse(uri.toString()).path + '/' + name + ".txt");
    }

    // ***存放章节信息***
    let chapters = [];  // 章节总信息，id, title, path 
    var tmpPath = outpath + '/' + name + '/';   // 小说所在目录
    let data = '';  // 当前行的小说数据
    let novel = ''; // 当前章节的小说数据
    let title = ''  // 当前章节的小说标题
    let id = 1; // 当前章节id
    var realPath = '';  // 当前章节路径
    
    // ***读取小说源文件，以分章节***
    var fileStream = fs.createReadStream(path);
    const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity,
    });
    
    // ***对小说源文件按行处理***
    for await (var line of rl) {
        data = line + '\n';
        
        // ***对章节进行处理***
        if(data.startsWith("===第")){
            // 第一个章节
            if (realPath == ''){
                realPath = tmpPath + line + '.txt';
                title = line;
                novel = novel.concat(data)
                continue;
            }
            console.log(novel);
            // 保存上一章节
            console.log(realPath);
            fs.writeFile(realPath, novel,()=>{})
            let chapter = {
                "id": id,
                "title":title,
                "path":realPath
            };
            chapters.push(chapter);
            title = line;
            id++;
            novel = ''
            realPath = tmpPath + line + '.txt';
        }
        novel = novel.concat(data)
    }


    // 处理最后一个章节
    fs.writeFile(realPath, novel,()=>{})
    id++;
    let chapter = {
        "id": id,
        "title":title
    };
    chapters.push(chapter);

    // 创建info.json 存储小说相关信息，章节信息，当前的阅读进度
    let content = {
        "name": name,
        "process":1,
        "Chapters": chapters
    };

    // 写入info.json
    let jsonString = JSON.stringify(content);
    fs.writeFile(outpath + '/' + name + '/info.json', jsonString,()=>{})
    console.log(jsonString);
}

function travel(dir){
    const path=require('path');
    var list = []
    var pathList = []
    fs.readdirSync(dir).forEach((file)=>{
        var pathname=path.join(dir,file)
        pathList.push(pathname)
        list.push(file)
    })
    return {
        'list':list,
        'pathList':pathList
    }
}

function getNovelList() {
    console.log(1111);
    let path = vscode.workspace.getConfiguration().get('moyu-plugin.novelPath');
    
    return travel(path)
}

module.exports = {
    parseNovel,
    setNovelPath,
    getNovelList
}